1.3.1 Defining and Using Methods as Functions
- A method is a function associated with an object.
- In JavaScript, functions are reusable blocks of code that perform a specific task. When a function is associated with an object, it's referred to as a method.
- Concepts:
- Functions: Defined using the function keyword or as arrow functions in ES6 (=>). They can be called directly by their name if they are not part of an object.
- Methods: When a function is a property of an object, it's called a method of that object. Methods are invoked on the object and can access and modify the object's properties.
- Example of defining and using methods:
// Defining an object with methods
var calculator = {
// Method to add two numbers
add: function(a, b) {
return a + b;
},
// Method to subtract two numbers
subtract: function(a, b) {
return a - b;
}
};
// Using the methods
var sum = calculator.add(5, 3); // Results in 8
var difference = calculator.subtract(5, 3); // Results in 2
// Defining a function (not associated with any object)
function greet(name) {
return "Hello, " + name + "!";
}
// Using the function
var greetingMessage = greet("Alice"); // Results in "Hello, Alice!"
1.3.2 Various Types of Functions
- Functions can be named, anonymous, or arrow functions.
- JavaScript supports multiple types of functions and function elements, each with unique characteristics and uses.
- Types of functions and their elements include:
- Prototype Functions: Functions attached to the prototype of an object, allowing all instances of the object to use the function.
- Anonymous Functions: Functions without a name, often used as arguments to other functions or as immediate function executions.
- Closure Functions: Functions that capture variables from their surrounding scope, allowing access to those variables even after the outer function has completed execution.
- Arguments: A special object available within all functions that contains an array-like list of all the arguments passed to the function.
- Return Values: Functions can return values using the return statement. If no return value is specified, a function will return undefined by default.
- Example implementations:
// Prototype Function
function Person(name) {
this.name = name;
}
// Adding a method to the prototype
Person.prototype.greet = function() {
return "Hello, my name is " + this.name;
};
var alice = new Person("Alice");
console.log(alice.greet()); // Outputs: "Hello, my name is Alice"
// Anonymous Function
setTimeout(function() {
console.log("This message is displayed after 2 seconds.");
}, 2000);
// Closure Function
function makeCounter() {
let count = 0; // Private variable
return function() {
count += 1; // Increment the count
return count; // Return the current count
};
}
const counter = makeCounter();
console.log(counter()); // Outputs: 1
console.log(counter()); // Outputs: 2
// Using arguments and return values
function sum() {
let total = 0;
for (let i = 0; i < arguments.length; i++) {
total += arguments[i]; // Add each argument to total
}
return total; // Return the total sum
}
console.log(sum(1, 2, 3, 4)); // Outputs: 10
1.3.3 Global vs. Local Variables
- Global variables are accessible anywhere, while local variables are confined to the function/block they are declared in.
- The scope of a variable determines where it can be accessed within the code.
- Definitions:
- Global Variables: Declared outside any function or declared without any keywords (var, let, const) inside a function. These variables can be accessed from any part of the code, including inside functions.
- Local Variables: Declared within a function or block (using var, let, or const). These variables are only accessible within the function or block in which they are declared.
- Example illustrating global vs. local variables:
// Global variable
var globalVar = "I am global";
function exampleFunction() {
// Local variable
var localVar = "I am local";
console.log(globalVar); // Accessible here, outputs: I am global
console.log(localVar); // Accessible here, outputs: I am local
}
exampleFunction();
console.log(globalVar); // Accessible here, outputs: I am global
// console.log(localVar); // Uncommenting this line will cause a ReferenceError: localVar is not defined
1.3.4 Using the Conditional (Ternary) Operator
- The ternary operator is a shorthand for if-else statements:
condition ? expressionIfTrue : expressionIfFalse
.
Study Guide: Section 1.3.4 - Using the Conditional (Ternary) Operator in JavaScript
Introduction to the Conditional Operator:
The conditional (ternary) operator is a concise way to execute conditional statements in JavaScript. It is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is true, followed by a colon (:), and finally the expression to execute if the condition is false. This operator provides a shorthand way to write simple if-else structures.
Syntax of the Conditional Operator:
condition ? expressionIfTrue : expressionIfFalse;
Examples:
1. Simple Example:
// Using the conditional operator to assign a value based on a condition
const age = 18;
const canVote = (age >= 18) ? 'Yes, you can vote.' : 'No, you cannot vote.';
console.log(canVote); // Output: Yes, you can vote.
2. Nested Conditional Operator:
// Using a nested conditional operator
const score = 85;
const grade = (score >= 90) ? 'A' :
(score >= 80) ? 'B' :
(score >= 70) ? 'C' :
(score >= 60) ? 'D' : 'F';
console.log(grade); // Output: B
1.3.5 User Events and Event Handlers
- User events (e.g.,
onclick
, onsubmit
) trigger event handlers, which are functions that respond to these events.
Study Guide: Section 1.3.5 - Identifying User Events and Event Handlers in JavaScript
Introduction to User Events and Event Handlers:
User events are actions or occurrences detected by the browser that interact with a web page, such as mouse clicks, keyboard input, resizing windows, or loading pages. Event handlers are JavaScript functions that are attached to elements to respond to these events.
Common User Events:
- Mouse Events: click, dblclick, mouseover, mouseout, mousedown, mouseup
- Keyboard Events: keydown, keyup, keypress
- Form Events: submit, change, focus, blur
- Document/Window Events: load, resize, scroll, unload
Event Handlers:
Event handlers respond to user events. They can be assigned directly in HTML using attributes like onclick
, or more commonly, using JavaScript with methods like addEventListener
.
Example of Implementing Event Handlers:
1. HTML Element:
<button id="myButton">Click Me!</button>
2. JavaScript to Handle the Button Click:
// Get the button element
const button = document.getElementById('myButton');
// Add an event listener for the click event
button.addEventListener('click', function() {
alert('Button was clicked!');
});
3. Handling a Keypress Event:
// Add an event listener for the keypress event on the document
document.addEventListener('keypress', function(event) {
console.log('Key pressed:', event.key);
});
1.3.6 Function-Specific Methods: call(), apply(), and bind()
call()
and apply()
invoke functions with a specified this
context, while bind()
creates a new function with a bound context.
Study Guide: Section 1.3.6 - Using Function-Specific Methods: Calling, Binding, and Applying in JavaScript
Introduction to Function-Specific Methods:
JavaScript provides several advanced methods to control the invocation of functions. These methods include call()
, bind()
, and apply()
, each serving unique purposes, particularly in managing the context (this
) or parameters of functions.
Definitions and Usage:
- call() Method: Allows you to call a function with a specified
this
value and arguments provided one by one. This method is useful when you know the number of arguments that the function will take.
- bind() Method: Creates a new function that, when called, has its
this
keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called. This is particularly useful for event handling and partial function application.
- apply() Method: Similar to
call()
, but instead of passing arguments one by one, you pass them as an array. This is useful when you don't know the number of arguments that the function will take.
Examples Demonstrating These Methods:
1. Using call()
:
function greet(greeting) {
return greeting + ', ' + this.name;
}
const person = { name: 'Alice' };
console.log(greet.call(person, 'Hello')); // Output: Hello, Alice
2. Using apply()
:
function introduce(language1, language2) {
return 'I speak ' + language1 + ' and ' + language2 + '.';
}
const languages = ['English', 'Spanish'];
console.log(introduce.apply(null, languages)); // Output: I speak English and Spanish.
3. Using bind()
:
function logName() {
console.log('Name:', this.name);
}
const user = { name: 'Bob' };
const boundLogName = logName.bind(user);
boundLogName(); // Output: Name: Bob
1.3.7 Built-In Functions and Casting Variables
- Use built-in functions like
parseInt()
, parseFloat()
, Number()
, and String()
for type conversion and data manipulation.
Study Guide: Section 1.3.7 - Using Built-in Functions and Casting Variables in JavaScript
Introduction to Built-in Functions and Variable Casting:
JavaScript provides a variety of built-in functions that help with common tasks like mathematical operations, converting data types, and more. Casting variables, often referred to as type conversion, involves changing a variable from one type to another, which is crucial in a dynamically typed language like JavaScript.
Common Built-in Functions:
- Mathematical Functions: Functions from the Math object, like
Math.round()
, Math.max()
, Math.min()
, and Math.random()
.
- Parsing Functions:
parseInt()
and parseFloat()
for converting strings to integers and floating-point numbers, respectively.
- String Functions: Includes
String.prototype
methods like toLowerCase()
, toUpperCase()
, charAt()
, slice()
, and more.
Variable Casting (Type Conversion):
- Explicit Conversion: Deliberately converting from one type to another using functions like
Number()
, String()
, or Boolean()
.
- Implicit Conversion: JavaScript automatically converts types in certain contexts, such as using the
+
operator with a number and a string (the number is converted to a string).
Examples Demonstrating Built-in Functions and Casting:
1. Using parseInt()
and parseFloat()
:
const intValue = parseInt('42'); // Converts string to integer
const floatValue = parseFloat('3.14'); // Converts string to floating-point number
console.log(intValue); // Output: 42
console.log(floatValue); // Output: 3.14
2. Using Number()
and String()
:
const num = Number('123'); // Converts string to number
const str = String(456); // Converts number to string
console.log(num); // Output: 123
console.log(str); // Output: "456"
3. Implicit Conversion Example:
const result = '5' + 5; // The number 5 is converted to a string
console.log(result); // Output: "55"